import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_architecture/src/features/weather/application/providers.dart';
import 'package:flutter_architecture/src/features/weather/domain/weather/weather_data.dart';
import 'package:flutter_architecture/src/features/weather/presentation/weather_icon_image.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

class HourlyWeather extends ConsumerWidget {
  const HourlyWeather({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final forecastDataValue = ref.watch(hourlyWeatherProvider);
    return forecastDataValue.when(data: (forecastData) {
      // API returns data points in 3-hour intervals -> 1 day = 8 intervals
      final items = [0, 8, 16, 24, 32];
      return HourlyWeatherRow(
        weatherDataList: [for (var i in items) forecastData.list[i]],
      );
    }, error: (error, stackTrace) {
      return Text(error.toString());
    }, loading: () {
      return const CircularProgressIndicator();
    });
  }
}

class HourlyWeatherRow extends StatelessWidget {
  final List<WeatherData> weatherDataList;

  const HourlyWeatherRow({super.key, required this.weatherDataList});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: weatherDataList
          .map((data) => HourlyWeatherItem(weatherData: data))
          .toList(),
    );
  }
}

class HourlyWeatherItem extends ConsumerWidget {
  final WeatherData weatherData;

  const HourlyWeatherItem({super.key, required this.weatherData});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final textTheme = Theme.of(context).textTheme;
    const fontWeight = FontWeight.normal;
    final temp = weatherData.temp.celsius.toInt().toString();
    return Expanded(
        child: Column(
      children: [
        Text(DateFormat.E().format(weatherData.date),
            style: textTheme.bodySmall?.copyWith(fontWeight: fontWeight)),
        const SizedBox(height: 8),
        WeatherIconImage(iconUrl: weatherData.iconUrl, size: 48),
        const SizedBox(height: 8),
        Text('$temp°',
            style: textTheme.bodyLarge?.copyWith(fontWeight: fontWeight)),
      ],
    ));
  }
}
